﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using TextFilesAppSupport;
using TextFilesAppDB;
using System.Threading;

namespace TextFilesController
{
    public class Controller
    {

        public static string Run(List<string> folderAddress)
        {
            Thread mainThread = new Thread(new ParameterizedThreadStart(ManageFile));

            mainThread.Start(folderAddress);

            return Warehouse.GetPopularWords(10).ToString();
        }

        public static void ManageFile(object filesAddress)
        {
            List<string> folderAddress = (List<string>)filesAddress;

            foreach (string file in folderAddress)
            {
                using (StreamReader input = new StreamReader(file))
                {
                    string text = input.ReadToEnd();
                    List<string> words = FormatString(text);

                    foreach (string word in words)
                    {
                        Warehouse.AddWordToBD(word);
                    }

                    input.Close();
                }
            }
        }

        private static List<string> FormatString(string text)
        {
            List<string> result = new List<string>();

            for (int i = 0; i < text.Length; i++)
            {
                if (text[i] != ' ')
                {
                    string word = String.Empty;

                    while (i < text.Length && text[i] != ' ' )
                    {
                        word = word + text[i];
                        i++;
                    }

                    result.Add(word);
                }
            }

            return result;
        }
    }
}
